package com.im.app.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.im.app.authConfig.CurrentUser;
import com.im.app.authConfig.RequireLogin;
import com.im.app.manager.ConversationManager;
import com.im.app.model.ChatLogs;
import com.im.app.model.Code;
import com.im.app.model.Conversations;
import com.im.app.model.User;
import com.im.app.service.*;
import com.im.app.utils.*;
import com.im.app.utils.uuid.IdUtils;
import org.jim.core.ImPacket;
import org.jim.core.packets.*;
import org.jim.core.utils.JsonKit;
import org.jim.server.JimServerAPI;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.*;


/**
 * 群组控制器
 */
@RestController
@RequestMapping(value = "/group")
public class IMGroupController {

    @Resource
    private IGroupService groupService;

    @Resource
    private IGroupMemberService groupMemberService;

    @Resource
    private ConversationsService conversationsService;

    @Resource
    private IPersonhostService personhostService;

    @Resource
    private ICodeService codeService;

    @Resource
    private ChatLogsService logsService;

    /**
     * 获取当前用户所有群组
     * @param user
     * @return
     */
    @RequireLogin
    @GetMapping("/getAllGroups")
    public ResponseResult<Object> getAllGroups(@CurrentUser User user){
        GroupMember groupMember =  new GroupMember();
        groupMember.setUserId(user.getUserId());
        List<GroupMember> list = groupMemberService.selectGroupMemberList(groupMember);
        List<Group> groups = new ArrayList<>();
        if(list.size() > 0){
            List<String> groupId = new ArrayList<>();
            for (GroupMember member: list) {
                groupId.add(member.getGroupId());
            }
            groups = groupService.selectGroupsByGroupIds(groupId.toArray(new String[groupId.size()]));
        }
        return Response.makeOKRsp().setData(groups);
    }

    /**
     * 查询群信息
     * @param groupId
     * @return
     */
    @RequireLogin
    @GetMapping("/getGroupInfo")
    public ResponseResult<Object> getGroup(String groupId){
        Group group = groupService.selectGroupsByGroupId(groupId);
        return Response.makeOKRsp().setData(group);
    }

    /**
     * 创建群
     * @param group
     * @return
     */
    @RequireLogin
    @PostMapping ("/addGroups")
    public ResponseResult<Object> addGroups(@CurrentUser User user,@RequestBody Group group){
        //判断登录账号是否为客服
        if(user.getAppMangerLevel() != 3){
           return Response.makeErrRsp("该账号没有操作权限");
        }
//        if(group == null || group.getKamicode() == null){
//            return Response.makeErrRsp("卡密为空");
//        }
//        Code code = codeService.getCodeByKamicode(group.getKamicode());
//        if(code == null){
//            return Response.makeErrRsp("群卡密有误");
//        }else if(!"useGroup".equals(code.getKamitype())){
//            return Response.makeErrRsp("卡密类型有误");
//        }else if(Constants.KAMIINUSE.equals(code.getKamistatus())){
//            return Response.makeErrRsp("群卡密已使用过");
//        }
        if (group.getName() == null){
            return Response.makeErrRsp("群昵称不能为空");
        }
        if (group.getAvatar() == null){
            return Response.makeErrRsp("群头像不能为空");
        }
        group.setGroupId(IdUtils.simpleUUID());
        group.setOwnerId(user.getUserId());
        group.setStatus(0);
        group.setMembers(new ArrayList<>());
        int result = groupService.insertGroups(group);
        if(result>0){
            //设置群主
            GroupMember groupMember = new GroupMember();
            groupMember.setGroupId(group.getGroupId());
            groupMember.setUserId(user.getUserId());
            groupMember.setAvatar(user.getAvatar());
            groupMember.setMute(0);
            groupMember.setNickname(user.getName());
            groupMember.setRole(GroupMemberType.ROLE_OWNER.getNumber());
            groupMember.setJoinTime(new Date());
            groupMemberService.insertGroupMember(groupMember);
            //分配群域名
//            personhostService.updateGroupOpration(group);
            //创建会话
            JimServerAPI.bindGroup(groupMember.getUserId(),group.getGroupId());
            ChatBody chatBody = group.updateMessageTip("群组创建成功");
            ChatLogs chatLogs = ChatLogs.bodyToLog(chatBody);
            logsService.insert(chatLogs);
            createGroupConversation(group,chatBody);
//            //修改卡密状态
//            code.setKamistatus(Constants.KAMIINUSE);
//            code.setUsetime(new Date());
//            codeService.updateById(code);
        }
        group = groupService.selectGroupsByGroupId(group.getGroupId());
        return Response.makeOKRsp(group);
    }

    /**
     * 创建会话记录
     */
    public void createGroupConversation(Group group,ChatBody chatBody){
        String userId = group.getOwnerId();
        String groupId = group.getGroupId();
        //游客会话
        Conversations gConversations = conversationsService.selectByGroup(userId,groupId);
        if(null == gConversations){
            Conversations conversations = new Conversations();
            String json = JsonKit.toJSONString(chatBody);
            conversations.setOwnerUserId(userId);
            conversations.setConversationId(IdUtils.simpleUUID());
            conversations.setGroupId(groupId);
            conversations.setConversationType(ChatType.CHAT_TYPE_PUBLIC.getNumber());
            conversations.setUnreadCount(0);
            conversations.setLastMessage(json);
            conversations.setAvatar(group.getAvatar());
            conversations.setNickName(group.getName());
            conversations.setIsPinned(0);
            conversations.setLastTime(new Date().getTime());
            ConversationManager.getManager().sendGroupChange(conversations);
            conversationsService.insert(conversations);
        }
    }

    /**
     * 修改群信息
     * @param group
     * @return
     */
    @RequireLogin
    @PostMapping("/updateGroups")
    public ResponseResult<Object> updateGroups(@CurrentUser User user,@RequestBody Group group){
        if(user.getAppMangerLevel() != 3){
            return  Response.makeErrRsp("该账号没有操作权限");
        }

        Group group1 = groupService.selectGroupsByGroupId(group.getGroupId());
        if (group1 == null){
            return  Response.makeErrRsp("没有对应群信息");
        }

        if (group.getAvatar() != null){
            group1.setAvatar(group.getAvatar());
        }
        if (group.getName() != null){
            group1.setName(group.getName());
        }
        if (group.getIntroduce() != null){
            group1.setIntroduce(group.getIntroduce());
        }

        if (group.getNotice() != null){
            group1.setNotice(group.getNotice());
        }

        if (group.getWelcome() != null){
            group1.setWelcome(group.getWelcome());
        }
        int result = groupService.updateGroups(group1);

        if(result>0){
            ChatBody chatBody = group1.updateMessageTip("群资料已更新");
            chatBody.setFrom(user.getUserId());
            JimServerAPI.sendGroupMessage(chatBody,user.getUserId());
            List<GroupMember> groupMembers = groupMemberService.selectGroupMemberByGroupId(group1.getGroupId());
            for (GroupMember groupMember : groupMembers){
                org.jim.core.packets.User byUser = JimServerAPI.getByUser(groupMember.getUserId());
                if (byUser != null){
                    if (byUser.getType() == 1){
                        updateGroupConversation(groupMember.getUserId(),group1.getGroupId());
                    }
                }
            }
            return Response.makeOKRsp("操作成功");
        }
        return Response.makeErrRsp("操作失败");
    }

    private void updateGroupConversation(String userId,String groupId){

        Conversations conversation = conversationsService.selectByGroup(userId, groupId);
        Group group = groupService.selectGroupsByGroupId(groupId);
        if(conversation != null){
            if (group != null){
                conversation.setAvatar(group.getAvatar());
                conversation.setNickName(group.getName());
            }
            ConversationManager.getManager().sendUserChange(conversation);
            conversationsService.update(conversation);
        }
    }


    @RequireLogin
    @PostMapping("/groupMute")
    public ResponseResult<Object> groupMute(@CurrentUser User user,@RequestBody Group group){
        if(user.getAppMangerLevel() != 3){
            return  Response.makeErrRsp("该账号没有操作权限");
        }
        int result = groupService.updateGroups(group);

        if(result>0){
            ImPacket imPacket = new ImPacket(Command.COMMAND_GROUP_MUTE_RESP,new RespBody(Command.COMMAND_GROUP_MUTE_RESP,group).toByte());
            JimServerAPI.sendToGroup(group.getGroupId(),imPacket);
            ChatBody chatBody = group.muteMessageTip();
            JimServerAPI.sendGroupMessage(chatBody,user.getUserId());
            return Response.makeOKRsp("操作成功");
        }
        return Response.makeErrRsp("操作失败");
    }

    @RequireLogin
    @PostMapping("/kickGroupMember")
    public ResponseResult<Object> kickGroupMember(@CurrentUser User user,@RequestBody GroupMember member){
        if(user.getAppMangerLevel() != 3){
            return  Response.makeErrRsp("该账号没有操作权限");
        }

        if (member.getGroupId() == null){
            return  Response.makeErrRsp("群ID不能为空");
        }

        if (member.getUserId() == null){
            return  Response.makeErrRsp("群成员ID不能为空");
        }

        GroupMember groupMember = groupMemberService.selectGroupMember(member.getGroupId(), member.getUserId());
        if (groupMember == null){
            return  Response.makeErrRsp("没有对应成员信息");
        }

        boolean result = groupMemberService.removeById(groupMember);
        if (result){
            JimServerAPI.unbindGroup(member.getUserId(),member.getGroupId());
            ImPacket imPacket = new ImPacket(Command.COMMAND_GROUP_MEMBER_KICK_RESP,new RespBody(Command.COMMAND_GROUP_MEMBER_KICK_RESP,groupMember).toByte());
            JimServerAPI.sendToUser(groupMember.getUserId(),imPacket);
            return  Response.makeOKRsp();
        }
        return Response.makeErrRsp("操作失败");
    }

    @RequireLogin
    @PostMapping("/updateGroupMemberMute")
    public ResponseResult<Object> updateGroupMemberMute(@CurrentUser User user,@RequestBody GroupMember groupMember){
        if(user.getAppMangerLevel() != 3){
            return  Response.makeErrRsp("该账号没有操作权限");
        }
        if(null == groupMember){
            return Response.makeErrRsp("参数异常");
        }
        if (groupMember.getGroupId() == null){
            return Response.makeErrRsp("群ID不能为空");
        }
        Group group = groupService.selectGroupsByGroupId(groupMember.getGroupId());
        if (group == null){
            return Response.makeErrRsp("没有对应群信息");
        }

        if (groupMember.getUserId() == null){
            return Response.makeErrRsp("群成员ID不能为空");
        }

        GroupMember groupMember1 = groupMemberService.selectGroupMember(groupMember.getGroupId(), groupMember.getUserId());
        if (groupMember1 == null){
            return Response.makeErrRsp("没有应对群成员信息");
        }

        groupMember1.setMute(groupMember.getMute());
        int result = groupMemberService.updateGroupMember(groupMember1);
        if(result>0){

            ImPacket imPacket = new ImPacket(Command.COMMAND_GROUP_MEMBER_MUTE_RESP,new RespBody(Command.COMMAND_GROUP_MEMBER_MUTE_RESP,groupMember1).toByte());
            JimServerAPI.sendToUser(groupMember.getUserId(),imPacket);

            ChatBody chatBody = group.muteMessageTip();
            chatBody.setContent(groupMember.getMute() == 0 ? groupMember1.getNickname() + "取消禁言" : groupMember1.getNickname() + "已被禁言");
            JimServerAPI.sendGroupMessage(chatBody,user.getUserId());



            return Response.makeOKRsp("操作成功");
        }
        return Response.makeErrRsp("操作失败");
    }


    /**
     * 删除群
     * @param groupId
     * @return
     */
    @RequireLogin
    @GetMapping("/deleteGroups")
    public ResponseResult<Object> deleteGroups(@CurrentUser User user, String groupId){
        if(user.getAppMangerLevel() != 3){
            return  Response.makeErrRsp("该账号没有操作权限");
        }
        int result = groupService.deleteGroupsByGroupId(groupId);
        if(result>0){
            //删除群成员信息
            groupMemberService.deleteGroupMemberByGroupId(groupId);
            //删除群会话
            //通知用户。。。

            return  Response.makeOKRsp("操作成功");
        }
        return Response.makeErrRsp("操作失败");
    }

}
